package com.example.grpc.factory;

import io.grpc.Server;
import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Component;

@Component
public class DefaultGrpcServerFactory implements GrpcServerFactory {
    @Autowired
    protected ApplicationContext applicationContext;
    @Override
    public Server createServer() {
        NettyServerBuilder serverBuilder =  NettyServerBuilder.forPort(8888);
        TaskExecutor taskExecutor = (TaskExecutor)applicationContext.getBean("grpcServiceExecutor");
        serverBuilder.executor(taskExecutor);
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                // Use stderr here since the logger may have been reset by its JVM shutdown hook.
                System.err.println("*** shutting down gRPC server since JVM is shutting down");
                this.stop();
                System.err.println("*** server shut down");
            }
        });

        serverBuilder.maxInboundMessageSize(32 << 20)
                .flowControlWindow(16 << 20);


        return serverBuilder.build();
    }


}
